package com.xhwl.logistics.strategy.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhwl.common.dto.cent.vehicle.SupplierConfigDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.vehicle.ParkSupplierEnum;
import com.xhwl.common.enums.vehicle.SyncTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.cent.vehicle.VehcParkingLot;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.vo.cent.vehicle.SyncVO;
import com.xhwl.logistics.dao.VehcParkingLotDao;
import com.xhwl.logistics.service.IVehcParkingLotService;
import com.xhwl.logistics.service.cent.IOrganizationService;
import com.xhwl.logistics.service.cent.IProductAccessCentService;
import com.xhwl.logistics.strategy.BasicInfoSyncStrategy;
import com.xhwl.logistics.strategy.InfoSyncSupplierStrategy;
import com.xhwl.logistics.strategy.context.InfoSyncSupplierStrategyContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 基础信息车场同步实现类
 * @author: lu.Aaron
 * @create: 2021-06-30 09:35
 **/
@Slf4j
//@Component
public class BasicInfoParkingLotSyncServiceImpl implements BasicInfoSyncStrategy {
    @Autowired
    private InfoSyncSupplierStrategyContext infoSyncSupplierStrategyContext;

    @Autowired
    private IProductAccessCentService productAccessCentService;

    @Autowired
    private VehcParkingLotDao vehcParkingLotDao;

    @Autowired
    private IVehcParkingLotService vehcParkingLotService;

    @Autowired
    private IOrganizationService organizationService;

    @Override
    public int getSyncType() {
        return SyncTypeEnum.PARKINGLOT.type;
    }

    @Override
    public ResultJson basicInfoSync(Short industryId, SyncVO syncVO) {
        log.info("同步车场信息开始(sync parking info start)");

        //先根据项目id和产品分类id查询供应商
        @NotNull Integer projectId = syncVO.getProjectId();
        @NotNull String parkId = syncVO.getParkId();
        @NotEmpty String projectName = syncVO.getProjectName();
        List<DeviceProjSupplierCategory> deviceProjSupplierCategories = productAccessCentService.listProductAccess(industryId, new ProductAccessQuery(projectId, CategoryEnum.YARD_GATE.getId()));
        if (deviceProjSupplierCategories.isEmpty()) {
            throw new BusinessException("该项目未配置供应商，请先配置");
        }
        DeviceProjSupplierCategory productAccess = deviceProjSupplierCategories.get(0);
        JSONObject properties = productAccess.getProperties();
        //获取供应商配置信息
        SupplierConfigDTO supplierConfigDTO = JSON.toJavaObject(properties, SupplierConfigDTO.class);
        //根据supplierId以及策略模式选取对应的接口实现类
        Integer supplierId = productAccess.getSupplierId();
        InfoSyncSupplierStrategy infoSyncSupplierService = infoSyncSupplierStrategyContext.getInfoSyncSupplierService(ParkSupplierEnum.getParkSupplierEnum(supplierId));
        //ParkingLotDTO parkingLotDTO = new ParkingLotDTO().setParkId(parkId);
        Map<String, Object> map = new HashMap<>();
        map.put("parkId",parkId);
        VehcParkingLot parkingLotFromSupplier = infoSyncSupplierService.getParkingLotInfo(map,supplierConfigDTO);
        if (Objects.isNull(parkingLotFromSupplier)) {
            throw new BusinessException("查询供应商该项目无车场信息");
        }
        //判断查询到车场是否已经在数据库了，在就不新增，不在就新增

        VehcParkingLot parkingLotFromDB = vehcParkingLotDao.selectOne(new QueryWrapper<VehcParkingLot>().eq("third_park_id", parkingLotFromSupplier.getThirdParkId()).eq("project_id",projectId));
        if (!Objects.isNull(parkingLotFromDB)) {
            throw new BusinessException("该车场已同步，请勿再同步");
        }

        syncParkingLotToOrg(industryId, projectId, parkingLotFromSupplier);
        //直接新增
        //设置项目id和项目名称
        parkingLotFromSupplier.setProjectId(projectId);
        parkingLotFromSupplier.setProjectName(projectName);
        vehcParkingLotService.save(parkingLotFromSupplier);

        log.info("同步车场信息结束(sync parking info end)");
        return ResultJson.success("同步车场成功");
    }

    private void syncParkingLotToOrg(Short industryId, @NotNull Integer projectId, VehcParkingLot parkingLotFromSupplier) {
        //根据projectId查询对应的organization信息
        OrganizationQuery organizationQuery = new OrganizationQuery();
        List<Integer> list = new ArrayList<>();
        list.add(projectId);
        organizationQuery.setProjectIds(list);
        organizationQuery.setIndustryId(industryId);
        List<OrganizationTypeEnum> organizationTypeEnums = new ArrayList<>();
        organizationTypeEnums.add(OrganizationTypeEnum.PROJECT);

        //cent-common修改OrganizationQuery withTypes方法已修改
        organizationQuery.withTypes(organizationTypeEnums.stream().map(organizationTypeEnum -> organizationTypeEnum.getId().intValue()).collect(Collectors.toList()));

        List<Organization> listFromCentDataCore = organizationService.list(organizationQuery);
        Organization organizationFrom = listFromCentDataCore.get(0);
        Integer level = organizationFrom.getLevel();
        Integer enterpriseId = organizationFrom.getEnterpriseId();
        Integer projectOrgId = organizationFrom.getId();
        Organization organization = new Organization();

        //cent-common修改Organization setType
        organization.setEnterpriseId(enterpriseId).setIndustryId(industryId).setParentId(projectOrgId).setLevel(level+1).setType(OrganizationTypeEnum.PARKING_LOT.getId().intValue()).setName(parkingLotFromSupplier.getName());

        //同步信息到organization表
        ResultJson<Integer> resultJson = organizationService.create(organization, new Account());
        if (!resultJson.getCode().equals(CodeEnum.SUCCESS.code)) {
            throw new BusinessException("与组织建立关系失败");
        }
        Integer orgId = resultJson.getResult();
        //处理listFromSupplier，将每一条数据对应的orgId更新到处理listFromSupplier
        parkingLotFromSupplier.setOrgId(orgId);
    }


}

